import { getOpenId, getUserInfo,getOpenIdCode } from "../../common/eduUserLogin";
export default {
	namespaced: true,
	state: { //存放状态
		eduToken: uni.getStorageSync('eduToken'),
		eduCode:uni.getStorageSync('eduCode'),
		eduUserInfo: uni.getStorageSync('eduUserInfo'),
		eduOpenid:uni.getStorageSync('eduOpenid')
	},
	/*action 提交的是 mutation，通过 mutation 来改变 state ，而不是直接变更状态*/
	actions: {
		async login(context, data) {
			context.commit("LOGIN", data);
			//获取userInfo
			await context.dispatch("setUserInfo",data.userCode);
			// #ifdef MP-WEIXIN
			await context.dispatch("setOpenid");
			// #endif
		},
		logOut(context) {
			context.commit('LOGOUT');
		},
		async setUserInfo(context,code) {
			const pages = getCurrentPages();
			const currentPagePath = pages.length > 0 ? pages[pages.length - 1].route : '';
							console.log(pages)
			let data = (await getUserInfo());
			let userInfo = {
				"userName":data.name,
				"userCode":data.userCode,
				"userId":data.id,
				"headImgUrl":data.headImgUrl,
				"userPhone":data.mobilePhone
			}
			console.log(userInfo);
			context.commit("SETUSERINFO", userInfo);
		},
		async setOpenid(context,data) {
			let code = await getOpenIdCode();
			let openid = ""
			if(code){
				console.log("----小程序获取登录code-----", code);
				openid = await getOpenId(code);
			}
			context.commit("SETOPENID", openid);
		},
		
	},
	/*改变数据的方法集合*/
	mutations: {
		LOGIN(state, data) {
			uni.setStorageSync("eduToken", data.token);
			uni.setStorageSync("eduCode", data.userCode);
			state.eduToken = data.token;
			state.eduCode = data.eduCode;
		},
		SETUSERINFO(state, info) {
			uni.setStorageSync("eduUserInfo", info);
			state.eduUserInfo = info
		},
		SETOPENID(state, data) {
			uni.setStorageSync("eduOpenid", data);
			state.eduOpenid = data
		},
		LOGOUT(state) {
			console.log('vuex logout');
			uni.removeStorageSync("eduToken");
			state.eduToken = null;
			uni.removeStorageSync("eduCode");
			state.eduCode = null;
			uni.removeStorageSync("eduUserInfo");
			state.eduUserInfo = null;
			uni.removeStorageSync("eduOpenid");
			state.eduOpenid = "";
			console.log("退出登录")
		},
	},
	/*对 state 的加工，是派生出来的数据*/
	getters: {
		isLogin(state) {
			return !!state.eduToken && !!state.eduUserInfo;
		},

	},
}